package com.wry.sharding.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDate;
import java.util.Collection;

/**
 * <h1> 按日期进行分表 <h1>
 *
 * @author wry
 * @since 2025/1/10 10:40
 */
@Slf4j
public class AttendanceShardingTableAlgorithm implements PreciseShardingAlgorithm<LocalDate> {


    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<LocalDate> shardingValue) {
        // 按此字段分片
        final LocalDate accessDate = shardingValue.getValue();
        // 实际表名
        String practiceTableName = shardingValue.getLogicTableName() + accessDate.getYear();
        if (accessDate.getMonth().getValue() < 10) {
            practiceTableName = practiceTableName + "0" + accessDate.getMonth().getValue();
        }else {
            practiceTableName = practiceTableName + accessDate.getMonth().getValue();
        }
        log.info("拼接表名 = {}", practiceTableName);
        if (tableNames.contains(practiceTableName)) {
            return practiceTableName;
        }
        log.error("取模精确分片策略：未找到与分片键匹配的表名! 逻辑表名[{}] : {} = {}", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());
        throw new UnsupportedOperationException();
    }
}
